package com.xxx.system.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xxx.jwt.JwtUtil;
import com.xxx.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行前端的请求
        String userType = request.getHeader("userType");
       if (!StrUtil.isBlank(userType)) {
           return true;
       }

        //1.从请求头中获取token
        String token = request.getHeader("token");  //56d96a2-1e9f-4e7a-a34b-1071a81cd9bf
        if (StrUtil.isBlank(token)) {
            //告诉浏览器我要给你响应一个json数据[自动将json格式的字符串-json对象]
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
            return false;
        }
        //2.校验token是否有效
        try {
            JwtUtil.parseJwtToken(token);
            return true; //放行 - 没有做刷新过期时间
        } catch (Exception e) {
            e.printStackTrace();
            //告诉浏览器我要给你响应一个json数据[自动将json格式的字符串-json对象]
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
            return false;
        }

    }
}